package com.hmall.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.item.mapper.ItemMapper;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Slf4j
@Service
public class ItemService extends ServiceImpl<ItemMapper, Item> implements IItemService {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Transactional
    @Override
    public void updateStatus(Long id, Integer status) {
        Item item = new Item();
        item.setStatus(status);
        item.setId(id);
        this.updateById(item);
        String exchangeName = "item.topic";
        String rontingKey = status == 1 ? "item.up" : "item.down";
        rabbitTemplate.convertAndSend(exchangeName,rontingKey,id);
        log.info("发送上下架消息：id：{}，状态：{}",id,status);
    }

    //扣除库存
    @Override
    public void deduct(Long itemId, Integer num) {
        Item item = this.getById(itemId);//库存字段为无符号数，如有超卖现象(库存为负数)，会抛异常
        this.update().set("stock",item.getStock()-num).eq("id",itemId).update();
    }

}
